<?php
 
declare (strict_types = 1);

namespace app\xapply\controller;

use app\base\BaseController;
use app\xapply\model\Category;
use think\facade\View;

class Group extends BaseController
{
    public function index()
    {
        if (request()->isAjax()) {
            $list = Category::where('id', '>', 0)->order('weigh', 'desc')->select()->toArray();
            $res['data'] = $list;
            return table_assign(0, '', $res);
        } else {
            return view();
        }
    }

    public function select(){
        $keyword = get_params('keyword');
        $list = Category::where('id', '>', 0)->order('weigh', 'desc')->select();
        $new = [];
        foreach ($list as $value){
            $new[] = [
                'name' => $value['name'],
                'value' => $value['id'],
                'selected' => $keyword && $keyword == $value['id'] ? 'selected' : '',
                'children' => [],
            ];
        }
        return to_assign(0, '',$new);
    }

    //添加&编辑
    public function add()
    {
        $param = get_params();
        $id = isset($param['id']) ? $param['id'] : 0;
        if ($id){
            $object = Category::find($id);
            View::assign('detail', $object);
        }else{
            View::assign('detail', []);
        }
        View::assign('id', $id);
        if (request()->isAjax()) {
            if ($id){

            }else{
                $object = new Category();
            }
            $object->save([
                'name' => $param['name'],
                'weigh' => $param['weigh'],
            ]);
            return to_assign();
        }
        return view();
    }

    public function delete()
    {
        $id = get_params("id");
        $object = Category::find($id);
        if ($object){
            $object->delete();
        }
        return to_assign(0, "删除分组成功");
    }
}
